﻿using AutoMapper;
using MediatR;
using Traceable.App.Application.Command.Goods;
using Traceable.Domian;
using Traceable.ErrorCode;
using Traceable.Infastructure;

namespace Traceable.App.Application.Handler.Goods
{
    public class UpdateGoodsTraceHandler : IRequestHandler<UpdateGoodsTraceCommand, ApiResult<int>>
    {
        private readonly IBaseRepository<Traceable_Table> _traceableRepository;
        private readonly IMapper _mapper;

        public UpdateGoodsTraceHandler(IBaseRepository<Traceable_Table> traceableRepository, IMapper mapper)
        {
            _traceableRepository = traceableRepository;
            _mapper = mapper;
        }
        /// <summary>
        /// 溯源基本信息修改
        /// </summary>
        /// <param name="request"></param>
        /// <param name="cancellationToken"></param>
        /// <returns></returns>
        /// <exception cref="NotImplementedException"></exception>
        public Task<ApiResult<int>> Handle(UpdateGoodsTraceCommand request, CancellationToken cancellationToken)
        {
            ApiResult<int> result = new ApiResult<int>();
            var traceable = _traceableRepository.GetAll().Where(p => p.Id == request.Id && !p.IsDelete).FirstOrDefault();
            if(traceable!=null)
            {
                traceable = _mapper.Map(request, traceable);
                traceable.UpdateTime = DateTime.Now;
                traceable.Updater = "张三";
            }
            var res = _traceableRepository.Update(traceable);
            if (res > 0)
            {
                result.Code = StatusEnum.OK;
                result.Data = res;
                result.Message = "修改成功";
            }
            else
            {
                result.Code = StatusEnum.Fail;
                result.Data = res;
                result.Message = "修改失败";
            }
            return Task.FromResult(result);


        }
    }
}
